/**********************************************
*  Classes:   CdnD3d9Renderer
*  Desc:      Renders geometry using Direct3D 9.
*             Singleton class - inherits from 
*		      CdnRenderer.
*  Author:    Vaios Kalpias-Ilias (C) 2008-2009
***********************************************/

#include "CdnD3d9Renderer.h"
#include "GeometryNode.h"
#include "Swap.h"
#include "Quaternion.h"
#include "Helper.h"
#include "GameApp.h"
#include "MaterialProperty.h"
#include "Camera.h"
#include "SkyBox.h"
#include <d3dx9.h>
#include <d3dx9math.h>

using namespace boost;

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

//-------------------------------------------------------------
/**
* Ctor
*/
CdnD3d9Renderer::CdnD3d9Renderer() :
m_D3d(0),
m_D3dDevice(0)
{

}
//-------------------------------------------------------------
/**
* Dtor
*/
CdnD3d9Renderer::~CdnD3d9Renderer()
{
	if (m_bWindowCreated)
	{
		DestroyRenderWindow();
	}
}
//-------------------------------------------------------------
/**
* Initializes renderer
*/
bool CdnD3d9Renderer::Init(HINSTANCE &hInstance, bool fullscreen,
						   int width, int height,
						   const char *title)
{

	if (!CreateRendererWindow(hInstance, fullscreen, width, height, title))
		return false;

	m_spCamera = CameraPtr(new Camera);


	return m_bInitialized = true;
	
}
//-------------------------------------------------------------
/**
* Creates a D3d9 window
*/
bool CdnD3d9Renderer::CreateRendererWindow(HINSTANCE &hInstance,
										   bool fullscreen, 
										   int width, int height, 
										   const char *title)
{
	m_iWidth = width;
	m_iHeight = height;
	m_fAspectRatio = (float)width / (float)height;

	unsigned int PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	m_bFullscreen = fullscreen;			// Set The Global Fullscreen Flag

	m_hInstance			= hInstance;				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) GameApp::MsgHandler;		// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= m_hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(0, IDI_WINLOGO);				// Load The Default Icon
	wc.hCursor			= LoadCursor(0, IDC_ARROW);				// Load The Arrow Pointer
	wc.hbrBackground	= 0;									// No Background Required For GL
	wc.lpszMenuName		= 0;									// We Don't Want A Menu
	wc.lpszClassName	= m_cfClassName;						// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(0,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;											// Return FALSE
	}

	if (m_bFullscreen)											// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= 32;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(0,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?",
				"Warning",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				m_bFullscreen = false;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(0,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (m_bFullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style		
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(m_hWnd=CreateWindowEx( dwExStyle,							
		m_cfClassName,					// Class Name
		title,								// Window Title
		dwStyle |							// Defined Window Style
		WS_CLIPSIBLINGS |					// Required Window Style
		WS_CLIPCHILDREN,					// Required Window Style
		0, 0,								// Window Position
		WindowRect.right-WindowRect.left,	// Calculate Window Width
		WindowRect.bottom-WindowRect.top,	// Calculate Window Height
		0,								// No Parent Window
		0,								// No Menu
		m_hInstance,					// Instance
		0)))							// Dont Pass Anything To WM_CREATE
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		32,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};

	if (!(m_hDC=GetDC(m_hWnd)))							// Did We Get A Device Context?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(m_hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	if(!SetPixelFormat(m_hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	// show window
	ShowWindow(m_hWnd,SW_SHOW);			// Show The Window
	SetForegroundWindow(m_hWnd);		// Slightly Higher Priority
	SetFocus(m_hWnd);

	// init d3d
	m_D3d = Direct3DCreate9(D3D_SDK_VERSION);    // create the Direct3D interface
	if (!m_D3d)
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Initialize Direct3d 9.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	D3DPRESENT_PARAMETERS d3dpp;    // create a struct to hold various device information

	ZeroMemory(&d3dpp, sizeof(d3dpp));    // clear out the struct for use
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
	d3dpp.Windowed = !m_bFullscreen;   
	if (!m_bFullscreen)
	{
		d3dpp.BackBufferWidth = m_iWidth;
		d3dpp.BackBufferHeight = m_iHeight;
	}
	d3dpp.EnableAutoDepthStencil = true;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;    // discard old frames
	d3dpp.hDeviceWindow = m_hWnd;    // set the window to be used by Direct3D

	// create a device class using this information and information from the d3dpp stuct
	m_D3d->CreateDevice(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		m_hWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp,
		&m_D3dDevice);

	if (!m_D3dDevice)
	{
		m_D3d->Release();
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Acquire Direct3d 9 Device","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;
	}

	m_D3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE);		 // turn on the z-buffer
	m_D3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);    // turn off the 3D lighting

	ResizeWindow(width, height);				// Set Up Our Perspective

	return m_bWindowCreated = true;									// Success
}	


//-----------------------------------------------
/**
* Destroys current window
*/
void CdnD3d9Renderer::DestroyRenderWindow()
{
	// shut down direct 3d 9
	if (m_D3d)
	{
		m_D3d->Release();
		m_D3d = 0;

		if (m_D3dDevice)
		{
			m_D3dDevice->Release();
			m_D3dDevice = 0;
		}
		
	}

	if (m_bFullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(0,0);					// If So Switch Back To The Desktop
		ShowCursor(true);								// Show Mouse Pointer
	}


	if (m_hDC && !ReleaseDC(m_hWnd,m_hDC))					// Are We Able To Release The DC
	{
		MessageBox(0,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		m_hDC=0;										// Set DC To 0
	}

	if (m_hWnd && !DestroyWindow(m_hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(0,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		m_hWnd=0;										// Set hWnd To 0
	}

	if (!UnregisterClass(m_cfClassName,m_hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(0,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		m_hInstance=0;									// Set hInstance To 0
	}

	m_bWindowCreated = false;
}

//-----------------------------------------------
/**
* Renders scene
*/

void CdnD3d9Renderer::RenderScene(SceneNode *scene)
{
	if (m_D3dDevice)
	{
		if (scene)
		{
			if (!m_spCamera->GetParent())
				m_spCamera->Update();

			if (m_spCamera->UpdateProjectionFlag())
			{
				ResizeWindow(m_iWidth, m_iHeight);
			}

			int r = (int)m_vBackgroundColor.x * 255;
			int g = (int)m_vBackgroundColor.y * 255;
			int b = (int)m_vBackgroundColor.z * 255;

			// clear the window to the background color
			m_D3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(r, g, b), 1.0f, 0);
			// clear z-buffer
			m_D3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

			m_D3dDevice->BeginScene();

			// setup OpenGL camera
			const mth::Vector3& pos    = m_spCamera->GetGlobalTranslation();
			const mth::Vector3& target = m_spCamera->GetTargetPos();
			const mth::Vector3& up =  m_spCamera->GetGlobalUp();
			D3DXMATRIX matView;    // the view transform matrix

			D3DXMatrixLookAtLH(&matView,
				&D3DXVECTOR3 (pos.x, pos.y, pos.z),             // the camera position
				&D3DXVECTOR3 (target.x, target.y, target.z),    // the look-at position
				&D3DXVECTOR3 (up.x, up.y, up.z));               // the up direction

			m_D3dDevice->SetTransform(D3DTS_VIEW, &matView);    // set the view transform to matView

			// sort states
			SortScene(scene);

			// render sorted geometry
			RenderSorted();

			// draw skybox
			if (m_spSkyBox)
			{

			}

			m_D3dDevice->EndScene();    // ends the 3D scene

			// clear sorted lists
			ClearSorted();

			m_D3dDevice->Present(0, 0, 0, 0);    // displays the created frame
		}
	}
	
	/*
	if (m_D3dDevice)
	{
		if (scene)
		{
			/*
			// update camera
			if (!m_spCamera->GetParent())
				m_spCamera->Update();

			if (m_spCamera->UpdateProjectionFlag())
			{
				ResizeWindow(m_iWidth, m_iHeight);
			}

			int r = (int)m_vBackgroundColor.x * 255;
			int g = (int)m_vBackgroundColor.y * 255;
			int b = (int)m_vBackgroundColor.z * 255;

			// clear the window to the background color
			m_D3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(r, g, b), 1.0f, 0);
			// clear z-buffer
			m_D3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

			m_D3dDevice->BeginScene();    // begins the 3D scene

			// setup OpenGL camera
			const mth::Vector3& pos    = m_spCamera->GetGlobalTranslation();
			const mth::Vector3& target = m_spCamera->GetTargetPos();
			const mth::Vector3& up =  m_spCamera->GetGlobalUp();
			D3DXMATRIX matView;    // the view transform matrix

			D3DXMatrixLookAtLH(&matView,
				&D3DXVECTOR3 (pos.x, pos.y, pos.z),             // the camera position
				&D3DXVECTOR3 (target.x, target.y, target.z),    // the look-at position
				&D3DXVECTOR3 (up.x, up.y, up.z));               // the up direction

			m_D3dDevice->SetTransform(D3DTS_VIEW, &matView);    // set the view transform to matView

		
			////////////////////////////////
			// sort states
			SortScene(scene);

			// render sorted geometry
			RenderSorted();

			// draw skybox
			if (m_spSkyBox)
			{

			}

			m_D3dDevice->EndScene();    // ends the 3D scene

			// clear sorted lists
			ClearSorted();

			m_D3dDevice->Present(0, 0, 0, 0);    // displays the created frame

		}

		
	}
	*/
	
}
//-----------------------------------------------
/**
* Resizes current window
*/
void CdnD3d9Renderer::ResizeWindow(int width, int height)
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	m_iWidth = width;
	m_iHeight = height;
	m_fAspectRatio = (float)width/(float)height;


	if (m_spCamera)
	{
		if (m_spCamera->UpdateProjectionFlag())
		{
			// set the projection transform
			D3DXMATRIX matProjection;
			D3DXMatrixPerspectiveFovLH(&matProjection,
				D3DXToRadian(m_spCamera->GetFOV()),
				m_fAspectRatio,
				m_spCamera->GetNearDist(),
				m_spCamera->GetFarDist());

			m_D3dDevice->SetTransform(D3DTS_PROJECTION, &matProjection); 
			
			m_spCamera->SetUpdateProjectionFlag(false);
		}
		else
		{
			// set the projection transform
			D3DXMATRIX matProjection;
			D3DXMatrixPerspectiveFovLH(&matProjection,
				D3DXToRadian(45.0f),
				m_fAspectRatio,
				1.0f,
				300.0f);

			m_D3dDevice->SetTransform(D3DTS_PROJECTION, &matProjection); 
			m_spCamera->SetUpdateFrustrum(true);
		}
	}
	else
	{
		// set the projection transform
		D3DXMATRIX matProjection;
		D3DXMatrixPerspectiveFovLH(&matProjection,
			D3DXToRadian(45.0f),
			m_fAspectRatio,
			1.0f,
			300.0f);
	}

	
}


//-----------------------------------------------
/**
* Sorts states in scene
*/
void CdnD3d9Renderer::SortScene(SceneNode *scene)
{
	if (scene->DerivesFromTransform())
	{
		if (!IsVisible(static_cast<TransformNode*>(scene)))
		{
			//return;
		}

	}
	else
		return;

	// if this is a geometry node
	if (scene->DerivesFromGeometry())
	{
		// create a SortStruct and add it 
		GeometryNode* geom = static_cast<GeometryNode*>(scene);

		TexturePropertyPtr tex  = static_pointer_cast<TextureProperty>
			(geom->GetProperty(NodeProperty::PROPERTY_TEXTURE));


		MaterialPropertyPtr mat  = static_pointer_cast<MaterialProperty>
			(geom->GetProperty(NodeProperty::PROPERTY_MATERIAL));

		unsigned int vboId = geom->GetVerticesName();

		TextureProperty* texP = 0;
		if (tex)
		{
			texP = tex.get();
		}

		MaterialProperty* matP = 0;
		if (mat)
		{
			matP = mat.get();
		}
		TexturesMap::iterator texIt = m_SortedGeometry.find(texP);
		if ( texIt != m_SortedGeometry.end())
		{
			MaterialMap::iterator matIt = texIt->second->find(matP);
			if (matIt != texIt->second->end())
			{
				GeometryMap::iterator geomIt = matIt->second->find(vboId);
				if (geomIt != matIt->second->end())
				{
					geomIt->second->push_back(geom);
					
				}
				else
				{
					GeometryList* l = new GeometryList;
					l->push_back(geom);
					matIt->second->insert(make_pair(vboId, l));
				}

			}
			else
			{
				GeometryList* l = new GeometryList;
				l->push_back(geom);
				GeometryMap* geomMap = new GeometryMap;
				geomMap->insert(make_pair(vboId, l));
				texIt->second->insert(make_pair(matP, geomMap));
			}
		}
		else
		{
			GeometryList* l = new GeometryList;
			l->push_back(geom);
			GeometryMap* geomMap = new GeometryMap;
			geomMap->insert(make_pair(vboId, l));
			MaterialMap* m = new MaterialMap;
			m->insert(make_pair(matP, geomMap));
			m_SortedGeometry.insert(make_pair(texP, m));
		}
	}

	// do the same for the children
	const SceneNode::NodeList children = scene->GetChildren();
	SceneNode::NodeList::const_iterator it;
	for (it = children.begin();
		it != children.end();
		++it)
	{
		SortScene((*it).get());
	}
}
//----------------------------------------------
/**
* Renders sorted geometry
*/
void CdnD3d9Renderer::RenderSorted()
{

	bool textureBinded = false;

	TexturesMap::iterator texIt = m_SortedGeometry.begin();
	for (; texIt != m_SortedGeometry.end(); ++texIt)
	{
		//textureBinded = false;
		TextureProperty* texture = texIt->first;
		if (texture)
		{
			//glEnable(GL_TEXTURE_2D);
			EnableTextures(texture);	

		}

		MaterialMap::iterator matIt = texIt->second->begin();

		for (; matIt != texIt->second->end(); ++matIt)
		{
			//bool materialBinded = false;
			MaterialProperty* material = matIt->first;
			if (material)
			{
				EnableMaterial(material);	
			}

			GeometryMap::iterator geomMapIt = matIt->second->begin();
			for (; geomMapIt != matIt->second->end(); ++geomMapIt)
			{
				bool vboBinded = false;
				GeometryNode* node = 0;
				GeometryList::iterator geomIt = geomMapIt->second->begin();
				for (; geomIt != geomMapIt->second->end(); ++geomIt)
				{
					node = *geomIt;

					EnableLights(node);

					if (!vboBinded)
					{
						vboBinded = true;
						EnableVertices(node);
						EnableNormals(node);
						EnableTexCoords(node);						
					}

					

					// transform 
					D3DXMATRIX matTranslate;
					const mth::Vector3& pos = node->GetGlobalTranslation();
					D3DXMatrixTranslation(&matTranslate, pos.x, pos.y, pos.z);

					D3DXMATRIX matRotate;
					float angle;
					mth::Vector3 axis;
					node->GetGlobalRotationQuat().GetAxisAngle(axis,angle);
					D3DXMatrixRotationAxis(&matRotate, &D3DXVECTOR3(axis.x, axis.y, axis.z), angle);
					

					D3DXMATRIX matScale;    
					const mth::Vector3& scale = node->GetScale();
					D3DXMatrixScaling(&matScale, scale.x, scale.y, scale.z);

					// tell Direct3D about our matrix
					m_D3dDevice->SetTransform(D3DTS_WORLD, &(matScale * matRotate * matTranslate));

					// render
					m_D3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

					DisableLights();
				}

				if (vboBinded && node)
				{
					DisableTexCoords(node);
					DisableNormals(node);
					DisableVertices(node);
				}

			}

		}

		if (texture)
		{
			//glDisable(GL_TEXTURE_2D);

		}
	}

}
//----------------------------------------------
/**
* Clears sorted geometry map
*/
void CdnD3d9Renderer::ClearSorted()
{
	TexturesMap::iterator it = m_SortedGeometry.begin();
	for (; it != m_SortedGeometry.end(); ++it)
	{
		MaterialMap::iterator mIt = it->second->begin();
		for(; mIt != it->second->end(); ++mIt)
		{
			GeometryMap::iterator gIt = mIt->second->begin();
			for (; gIt != mIt->second->end(); ++gIt)
			{
				gIt->second->clear();
				delete gIt->second;
			}
			mIt->second->clear();
			delete mIt->second;
		}

		it->second->clear();
		delete it->second;
	}

	m_SortedGeometry.clear();

}
//-----------------------------------------------
/**
* Sets the environment state for a texture
*/
void CdnD3d9Renderer::SetTextureEnvState(unsigned int texId, 
										 TextureProperty::EnvironmentState state)
{
	if (texId)
	{
		
		switch (state)
		{
		case TextureProperty::STATE_MODULATE:
			
			break;

		case TextureProperty::STATE_BLEND:
			
			break;

		case TextureProperty::STATE_REPLACE:
			
			break;
		default:
			return;
		}
	}

}
//-----------------------------------------------
/**
* Enables vertices
*/
void CdnD3d9Renderer::EnableVertices(GeometryNode* node)
{
	if (node->GetVerticesName())
	{
		m_D3dDevice->SetFVF(CUSTOMFVF);
		LPDIRECT3DVERTEXBUFFER9 pBuffer = (LPDIRECT3DVERTEXBUFFER9)node->GetVoidData();
		m_D3dDevice->SetStreamSource(0, pBuffer, 0, sizeof(D3dVertex));
	}
}
//-----------------------------------------------
/**
* Disables vertices
*/
void CdnD3d9Renderer::DisableVertices(GeometryNode* node)
{
	if (node->GetVerticesName())
	{
		
	}
}
//-----------------------------------------------
/**
* Enables normals
*/
void CdnD3d9Renderer::EnableNormals(GeometryNode* node)
{
	if (node->GetNormalsName())
	{
		
	}
}
//-----------------------------------------------
/**
* Disables normals
*/
void CdnD3d9Renderer::DisableNormals(GeometryNode* node)
{
	if (node->GetNormalsName())
	{
		
	}
}
//-----------------------------------------------
/**
* Enables tex coords
*/
void CdnD3d9Renderer::EnableTexCoords(GeometryNode* node)
{
	if (node->GetTexCoordsName())
	{
		
	}
}
//-----------------------------------------------
/**
* Disables tex coords
*/
void CdnD3d9Renderer::DisableTexCoords(GeometryNode* node)
{
	if (node->GetTexCoordsName())
	{
		
	}
}
//-----------------------------------------------
/**
* Enables textures
*/
void CdnD3d9Renderer::EnableTextures(TextureProperty* tex)
{
	
}
//-----------------------------------------------
/**
* Enables a material
*/
void CdnD3d9Renderer::EnableMaterial(MaterialProperty* mat)
{	
	const mth::Vector3& ambient = mat->GetAmbient();
	const mth::Vector3& diffuse = mat->GetDiffuse();
	const mth::Vector3& specular = mat->GetSpecular();
	const mth::Vector3& emissive = mat->GetEmissive();
	float alpha = mat->GetAlpha();
	float ambientv[] = {ambient.x, ambient.y, ambient.z, 1.0f};
	float diffusev[] = {diffuse.x, diffuse.y, diffuse.z, alpha};
	float specularv[] = {specular.x, specular.y, specular.z, 1.0f};
	float emissivev[] = {emissive.x, emissive.y, emissive.z, 1.0f};
	float shininess = mat->GetShininess();
	
}

//-----------------------------------------------
/**
* Enables lights for a node
*/
void CdnD3d9Renderer::EnableLights(GeometryNode* node)
{
	const TransformNode::LightList& lights =
		node->GetLightList();

	TransformNode::LightList::const_iterator it;
	unsigned int num = 0;
	for (it = lights.begin();
		it != lights.end();
		++it)
	{
		if ((*it)->IsOn())
			EnableLight((*it), num);
		if (++num > GetMaxLights()) return;
	}
}
//-----------------------------------------------
/**
* Enables one of 8 lights
*/
void CdnD3d9Renderer::EnableLight(LightPtr light,
							 unsigned int num)
{
	const mth::Vector3& ambient = light->GetAmbient();
	const mth::Vector3& diffuse = light->GetDiffuse();
	const mth::Vector3& specular = light->GetSpecular();
	const mth::Vector3& pos = light->GetPosition();
	float ambientv[] = {ambient.x, ambient.y, ambient.z, 1.0f};
	float diffusev[] = {diffuse.x, diffuse.y, diffuse.z, 1.0f};
	float specularv[] = {specular.x, specular.y, specular.z, 1.0f};
	float posv[] = {pos.x, pos.y, pos.z, 1.0f};
	/*
	switch (num)
	{
	
	default:
		return;
	}
	*/
}
//-----------------------------------------------
/**
* Disables lighting
*/
void CdnD3d9Renderer::DisableLights()
{
	
}
//----------------------------------------------
/**
* Creates vertices, normals etc for a node
*/
bool CdnD3d9Renderer::BindNodeToMesh(GeometryNode* node,
								mth::Vector3* vertices,
								mth::Vector3* normals,
								mth::Vector2* texCoords,
								int numOfVertices)
{

	
	RenderStruct* renderStruct = new RenderStruct();
	static unsigned int vboName = 0;
	vboName++;

	D3dVertex t_vert[] =
	{
		{ 320.0f, 50.0f, 0.5f, D3DCOLOR_XRGB(0, 0, 255), },
		{ 520.0f, 400.0f, 0.5f,  D3DCOLOR_XRGB(0, 255, 0), },
		{ 120.0f, 400.0f, 0.5f,  D3DCOLOR_XRGB(255, 0, 0), },
	};

	LPDIRECT3DVERTEXBUFFER9 t_buffer;

	m_D3dDevice->CreateVertexBuffer(3*sizeof(D3dVertex),
		0,
		CUSTOMFVF,
		D3DPOOL_MANAGED,
		&t_buffer,
		NULL);

	VOID* pVoid;    // the void pointer

	t_buffer->Lock(0, 0, (void**)&pVoid, 0);    // lock the vertex buffer
	memcpy(pVoid, t_vert, sizeof(t_vert));    // copy the vertices to the locked buffer
	t_buffer->Unlock();    // unlock the vertex buffer

	renderStruct->numOfVertices = numOfVertices;
	renderStruct->verticesName = vboName;
	renderStruct->pBuffer = t_buffer;
	renderStruct->normalsName = 0;
	renderStruct->texCoordsName = 0;
	m_lRenderStructs.push_back(renderStruct);

	

	node->SetVoidData((LPDIRECT3DVERTEXBUFFER9)t_buffer);
	node->SetVerticesName(renderStruct->verticesName);
	node->SetNormalsName(renderStruct->normalsName);
	node->SetTexCoordsName(renderStruct->texCoordsName);
	node->SetNumOfVertices(renderStruct->numOfVertices);

	return true;
}

//----------------------------------------------
/**
* Debug code to show bounding boxes
*/
void CdnD3d9Renderer::ShowBoundingBoxes(GeometryNode* node)
{

	const BoundingBox& b = node->GetBoundingBox();
	mth::Vector3 nearUpL(b.minX, b.maxY, b.maxZ);
	mth::Vector3 nearUpR(b.maxX, b.maxY, b.maxZ);
	mth::Vector3 nearDownL(b.minX, b.minY, b.maxZ);
	mth::Vector3 nearDownR(b.maxX, b.minY, b.maxZ);
	mth::Vector3 farUpL(b.minX, b.maxY, b.minZ);
	mth::Vector3 farUpR(b.maxX, b.maxY, b.minZ);
	mth::Vector3 farDownL(b.minX, b.minY, b.minZ);
	mth::Vector3 farDownR(b.maxX, b.minY, b.minZ);

}
//----------------------------------------------
/**
* Unloads vertex buffers etc
*/
void CdnD3d9Renderer::UnloadGeometry()
{
	if (m_bInitialized)
	{
		RenderList::iterator it;
		for (it = m_lRenderStructs.begin();
			it != m_lRenderStructs.end();
			++it)
		{
			
			(*it)->pBuffer->Release();
			delete (*it);
		}

		m_lRenderStructs.clear();
	}


	ClearSorted();

}
